package com.example.damaizuul.web;

import com.example.damaizuul.util.JwtUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * Company 源辰信息
 *
 * @author navy
 * @date 2024/6/26
 * Email haijunzhou@hnit.edu.cn
 */
@Component
public class LoginFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "post";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        List<String> list = Arrays.asList("/user/lg/login", "/user1/lg/login", "/damai-user/lg/login");
        if (list.contains(request.getServletPath())) {
            return true;
        }
        return false;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        InputStream in = currentContext.getResponseDataStream();
        byte[] bytes = new byte[1024];
        try {
            int count = in.read(bytes);
            String json = new String(bytes,0,count);
            ObjectMapper mapper = new ObjectMapper();
            Map map = mapper.readValue(json, Map.class);
            if ((map.get("code")+"").equals("1")) {
                // 登录成功
                Map user = (Map) map.get("data");
                String jwt = JwtUtil.createJWT(30, user);
                currentContext.getResponse().addHeader("Authorization",jwt);
            }
            currentContext.setResponseStatusCode(200);
            currentContext.getResponse().setContentType("application/json;charset=utf-8");
            currentContext.setResponseBody(json);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    }
}
